<template>
  <el-card class="box-card">
    <div class="container">
      <p>{{ form.id ? "试题修改" : "试题录入" }}</p>
      <el-divider></el-divider>
      <el-form ref="add" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学科:" prop="subjectID" :rules="rules.subjectID">
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="form.subjectID"
            @focus="courseFn"
          >
            <el-option
              v-for="(item, index) in courseList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select
            v-model="form.catalogID"
            placeholder="请选择"
            style="width: 400px"
            @focus="listFn"
          >
            <el-option
              v-for="(item, index) in listList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select
            v-model="form.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in enterpriseList"
              :key="index"
              :label="item.shortName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="city">
          <el-select
            v-model="form.province"
            placeholder="请选择"
            style="width: 198px; margin-right: 4px"
            @focus="provinces"
          >
            <el-option
              v-for="(item, index) in cityList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.city"
            placeholder="请选择"
            style="width: 198px"
            @focus="citys"
          >
            <el-option
              v-for="(item, index) in citysList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向:" prop="direction">
          <el-select
            v-model="form.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="form.questionType">
            <el-radio
              v-for="(item, index) in questionTypeList"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio
              v-for="(item, index) in difficultyList"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <!-- <el-input type="textarea" v-model="form.desc"></el-input> -->

          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 150px; overflow-y: hidden"
              v-model="form.question"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
        <el-form-item
          v-if="form.questionType !== '3'"
          label="选项:"
          prop="options"
        >
          <div v-for="(item, index) in form.options" :key="index" class="wrap">
            <div class="radio">
              <el-radio
                v-if="form.questionType === '1'"
                v-model="radio"
                :label="item.code"
                @change="radiochange"
                >{{ item.code }}:
              </el-radio>
            </div>
            <div v-if="form.questionType === '2'" class="check">
              <el-checkbox @change="checkboxchange" v-model="item.check"
                >{{ item.code }}:
              </el-checkbox>
            </div>
            <el-input
              type="text"
              v-model="item.title"
              style="width: 240px; margin: 5px"
            ></el-input>
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="item.img" :src="item.img" class="avatar" />
              <i v-else>上传图片</i>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <el-button
            @click="addoption"
            :disabled="form.questionType === '1'"
            type="danger"
            size="small"
            >+添加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频:">
          <el-input v-model="form.videoURL" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor2"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 150px; overflow-y: hidden"
              v-model="form.answer"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated2"
            />
          </div>
        </el-form-item>
        <el-form-item label="题目备注:" prop=" remarks">
          <el-input
            type="textarea"
            :autosize="{ minRows: 5, maxRows: 10 }"
            v-model="form.remarks"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="tagsList.length" label="试题标签:">
          <el-select
            v-model="value"
            placeholder="请选择"
            style="width: 400px"
            multiple
            filterable
            allow-create
            default-first-option
          >
            <el-option
              v-for="(item, index) in tagsList"
              :key="index"
              :label="item.tagName"
              :value="item.tagName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            :type="form.id ? 'success' : 'primary'"
            @click="onSubmit"
            >{{ form.id ? "确定修改" : "确定提交" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { simple } from '@/api/hmmm/subjects'
import { simple as subjectsDetail } from '@/api/hmmm/directorys'
import { list as listname } from '@/api/hmmm/companys'
import { list as list1 } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { add, update, detail } from '@/api/hmmm/questions'
export default {
  data () {
    return {
      value: [],
      radio: null,

      form: {
        id: '', // id
        subjectID: '', // 学科
        catalogID: '', // 目录
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        answer: '', // 答案解析
        direction: '', // 方向
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 0
          },
          { code: 'B', title: '', img: '', isRight: 1 },
          { code: 'C', title: '', img: '', isRight: 0 },
          { code: 'D', title: '', img: '', isRight: 0 }
        ], // 选项
        tags: '', // 试题标签
        remarks: '', // 题目备注
        videoURL: '' // 解析视频
      },
      courseList: '', // 学科列表
      listList: [], // 目录列表
      enterpriseList: '', // 企业列表
      directionList: direction, // 方向列表
      cityList: '', // 地区列表
      citysList: '', // 分地区列表
      questionTypeList: questionType.map((i) => {
        return {
          value: String(i.value),
          label: i.label
        }
      }), // 题型
      difficultyList: difficulty.map((i) => {
        return {
          value: String(i.value),
          label: i.label
        }
      }), // 难度
      tagsList: '', // 试题列表
      rules: {
        subjectID: [{ required: true, message: '请选择学科' }],
        catalogID: [{ required: true, message: '请选择目录' }],
        direction: [{ required: true, message: '请选择方向' }],
        questionType: [{ required: true, message: '请选择' }],
        enterpriseID: [{ required: true, message: '请选择企业' }],
        difficulty: [{ required: true, message: '请选择' }],
        province: [{ required: true, message: '请选择地区' }],
        city: [{ required: true, message: '请选择地区' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }]
      },
      editor: null,
      toolbarConfig: {
        toolbarKeys: [
          // // 菜单 key
          // 'headerSelect',

          // // 分割线
          // '|',

          // 菜单 key
          'bold',
          'underline',
          'italic',
          'through',
          'bulletedList',
          'numberedList',
          'blockquote',
          'codeBlock',
          'insertImage',
          'insertLink'

          // 菜单组，包含多个菜单
          // {
          //   key: 'group-more-style', // 必填，要以 group 开头
          //   title: '更多样式', // 必填
          //   iconSvg: '<svg>....</svg>', // 可选
          //   menuKeys: ['through', 'code', 'clearStyle'] // 下级菜单 key ，必填
          // }
          // 继续配置其他菜单...
        ]
      },
      editorConfig: { placeholder: '' },
      editor2: null,
      mode: 'simple' // or 'simple'
    }
  },
  created () {
    this.form.id = this.$route.query.id ? this.$route.query.id : this.form.id
    this.courseFn()
    // this.listFn()
    this.enterpriseFn()
    this.tagsListFn()
    if (this.$route.query.id) {
      this.detailFn()
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    addoption () {
      const S = String.fromCharCode(
        this.form.options[this.form.options.length - 1].code.charCodeAt(0) + 1
      )
      this.form.options.push({ code: S, title: '', img: '', isRight: 0 })
    },
    radiochange (e) {
      // console.log(e, 'e')
      this.form.options.forEach((i) => (i.isRight = 0))
      this.form.options.forEach((item) => {
        if (item.code === e) {
          item.isRight = 1
        }
      })
      // console.log(this.form.options, 'this.form.options')
    },
    checkboxchange () {
      this.form.options.forEach((item) => {
        if (item.check) {
          item.isRight = 1
        }
      })
      // console.log(this.form.options, 'this.form.options')
    },
    // adsasd (e) {
    //   console.log(e, 'e')
    // },
    // // 提交 或 修改按钮 点击事件
    async onSubmit () {
      try {
        this.form.answer =
          this.form.answer === '<p><br></p>' ? '' : this.form.answer
        this.form.question =
          this.form.question === '<p><br></p>' ? '' : this.form.question
        await this.$refs.add.validate()
        // console.log(this.form.tags)
        if (this.form.id) {
          this.form.tags = this.value.join()
          this.form.questionType = String(this.form.questionType)
          // console.log(this.form, 'this.form')
          await update(this.form)
          this.$message.success('修改成功') // 成功提示
          this.$router.back() // 回到上一个页面
        } else {
          // console.log(this.form)
          this.form.tags = this.value.join()
          await add(this.form)
          this.$message.success('提交成功') // 成功提示
          this.$router.push('/questions/list')
        }
      } catch (error) {}
    },
    onCreated (editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onCreated2 (editor) {
      this.editor2 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // editor.clear()
    },
    // 获取学科列表
    async courseFn () {
      this.form.catalogID = ''
      const { data } = await simple()
      this.courseList = data
      console.log(this.courseList)
      // this.listFn()
    },
    // 获取目录列表
    async listFn () {
      if (this.form.subjectID) {
        const { data } = await subjectsDetail({
          subjectID: this.form.subjectID
        })
        this.listList = data
        console.log(data)
      }

      // console.log(this.listList)
    },
    // 获取企业列表
    async enterpriseFn () {
      const { data } = await listname()
      this.enterpriseList = data.items
      // console.log(this.enterpriseList)
    },
    // 获取地区列表
    provinces () {
      this.cityList = provinces()
      this.form.city = ''
    },
    // 获取分地区列表
    citys () {
      this.citysList = citys(this.form.province)
    },
    // 获取试题标签列表
    async tagsListFn () {
      const { data } = await list1()
      this.tagsList = data.items
      // console.log(data.items)
    },
    // 基础题库详情
    async detailFn () {
      const { data } = await detail({ id: this.form.id })
      // console.log(data.tags, 'this.form.tags')
      // console.log(data)
      if (data.tags) {
        this.value = data.tags.split(',')
      }
      data.options.forEach((item) => {
        if (item.isRight === 1) {
          item.check = true
          this.radio = item.code
        }
      })
      this.form = data
      this.listFn()
    }
  },

  components: { Editor, Toolbar }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css">
</style>
<style scoped lang='scss'>
.box-card {
  margin: 20px;
  // margin-right: 30px;

  // width: 100%;
}
.container {
  p {
    margin-left: 20px;
  }
}
:deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  width: 100px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
:deep .avatar-uploader .el-upload:hover {
  border: 1px dashed #0da5fa;
}
.wrap {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
  margin-top: -5px;
  margin-right: -5px;
  z-index: 99999;
  background: #ffffff;
}
</style>
